<template>
  <div class="roleDialog">
    <el-dialog
      :title="title"
      :visible="visible"
      @update:visible="$emit('update:visible', $event)"
      @closed="Onclosed"
    >
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item
          label="角色名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="角色描述"
          :label-width="formLabelWidth"
          prop="description"
        >
          <el-input v-model="form.description" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addRoles, editRolesId } from '@/api/setting'
export default {
  props: {
    form: Object,
    visible: Boolean
  },
  data() {
    return {
      formLabelWidth: '120px',
      // 表单验证
      rules: {
        name: [{ required: true, message: '不能为空', trigger: 'change' }],
        description: [
          { required: true, message: '不能为空', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    title() {
      return this.form.id ? '编辑角色' : '新增角色'
    }
  },
  // watch: {
  //   visible(val) {
  //     if (!val) this.$refs.form.resetFields()
  //   }
  // },
  methods: {
    submitRole() {
      this.$refs.form.validate(async(flag) => {
        if (flag) {
          // 如果有id，则是编辑角色
          if (this.form.id) {
            const res = await editRolesId(this.form)
          } else {
            const res = await addRoles(this.form)
          }
          // 弹出成功信息
          this.$message.success(`${this.title}成功`)
          // 获取角色数据
          this.$emit('getRole')
          // 关闭弹出框
          this.$emit('clear')
        } else {
          this.$message.warning('输入格式有误')
          return false
        }
      })
    },

    // 关闭弹窗时重置表单验证
    Onclosed() {
      this.$refs.form.resetFields()
      this.$emit('clear')
    }
  }
}
</script>

<style></style>
